package com.vxfly.helioscamera.function;

import android.content.ContentResolver;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

import com.vxfly.helioscamera.SDKAPI.FileOperation;
import com.vxfly.helioscamera.Tool.FileTools;
import com.vxfly.helioscamera.global.App.GlobalInfo;
import com.vxfly.helioscamera.global.sdk.SDKSession;
import com.vxfly.helioscamera.log.WriteLogToDevice;
import com.icatch.wificam.customer.ICatchWificamPlayback;
import com.icatch.wificam.customer.exception.IchInvalidSessionException;
import com.icatch.wificam.customer.type.ICatchFrameBuffer;

public class ThumbnailOperation {
	private static String TAG = "ThumbnailOperation";
	
	public static Bitmap getVideoThumbnailFromSdk(String videoPath) {
		WriteLogToDevice.writeLog(TAG, "start getVideoThumbnailFromSdk");
        ICatchWificamPlayback cameraPlayback = null;
        Bitmap bitmap = null;
        ICatchFrameBuffer frameBuffer = null;
        int datalength= 0;
        byte[] buffer = null;
        SDKSession sdkSession = new SDKSession();
        if(!sdkSession.prepareSession("192.168.1.1",false)){
        	WriteLogToDevice.writeLog(TAG, "getVideoThumbnailFromSdk false");
            return null;
        }
        try {
            cameraPlayback = sdkSession.getSDKSession().getPlaybackClient();
        } catch (IchInvalidSessionException e) {
            e.printStackTrace();
        }
        frameBuffer = FileOperation.getInstance().getThumbnail(cameraPlayback,videoPath);
        if(frameBuffer != null){
            buffer = frameBuffer.getBuffer();
            datalength = frameBuffer.getFrameSize();
            if (datalength > 0) {
                bitmap = BitmapFactory.decodeByteArray(buffer, 0, datalength);
            }
        }
        sdkSession.destroySession();
        WriteLogToDevice.writeLog(TAG, "end getVideoThumbnailFromSdk bitmap=" + bitmap);
        return bitmap;
    }
	
	public static Bitmap getVideoThumbnail(Context context,String videoPath){
		WriteLogToDevice.writeLog(TAG, "start getVideoThumbnail videoPath=" + videoPath);
		if(videoPath == null){
			return null;
		}
		ContentResolver resolver = GlobalInfo.getInstance().getCurrentApp().getContentResolver();
        Bitmap bitmap = FileTools.getVideoThumbnail(context ,resolver,videoPath);
        if(bitmap == null){
            bitmap = getVideoThumbnailFromSdk(videoPath);
        }
        WriteLogToDevice.writeLog(TAG, "end getVideoThumbnail bitmap=" + bitmap);
        return bitmap;
    }

}
